<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="####1. 错误与异常1). try语句按照如下方式工作；首先，执行try子句（在关键字try和关键字except之间的语句）;如果没有异常发生，忽略except子句，try子句执行后结束; 如果在执行try子句的过程中发生了异常，那么try子句余下的部分将被忽略。如果异常的类型和 except 之后的名称相符，那么对应的except子句将被执行。最后执行 try 语句之后的代码; 如果一个异常">
<meta name="keywords" content="Android、iOS、Web、React Native">
<meta property="og:type" content="article">
<meta property="og:title" content="Python-学习(五)">
<meta property="og:url" content="http://yoursite.com/blog/2018/08/06/Python/Python-学习(五)/index.html">
<meta property="og:site_name" content="凌浩雨_博客">
<meta property="og:description" content="####1. 错误与异常1). try语句按照如下方式工作；首先，执行try子句（在关键字try和关键字except之间的语句）;如果没有异常发生，忽略except子句，try子句执行后结束; 如果在执行try子句的过程中发生了异常，那么try子句余下的部分将被忽略。如果异常的类型和 except 之后的名称相符，那么对应的except子句将被执行。最后执行 try 语句之后的代码; 如果一个异常">
<meta property="og:locale" content="default">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-d10119bc65d6daac.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-2e0769462475f359.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-cc20d842935f85be.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-8163c57f4fa5533f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-f418655bab3398c6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-807821048049a408.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-99933e06548fc5af.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-2ce8dc17fb620231.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-b47c866903de51bd.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-5e07170991cf225a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-08-06T10:32:43.753Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Python-学习(五)">
<meta name="twitter:description" content="####1. 错误与异常1). try语句按照如下方式工作；首先，执行try子句（在关键字try和关键字except之间的语句）;如果没有异常发生，忽略except子句，try子句执行后结束; 如果在执行try子句的过程中发生了异常，那么try子句余下的部分将被忽略。如果异常的类型和 except 之后的名称相符，那么对应的except子句将被执行。最后执行 try 语句之后的代码; 如果一个异常">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/3110861-d10119bc65d6daac.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/blog/2018/08/06/Python/Python-学习(五)/"/>





  <title>Python-学习(五) | 凌浩雨_博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">凌浩雨_博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/blog/blog/2018/08/06/Python/Python-学习(五)/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="凌浩雨">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="凌浩雨_博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Python-学习(五)</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-08-06T18:01:39+08:00">
                2018-08-06
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>####1. 错误与异常<br>1). try语句按照如下方式工作；<br>首先，执行try子句（在关键字try和关键字except之间的语句）;如果没有异常发生，忽略except子句，try子句执行后结束; 如果在执行try子句的过程中发生了异常，那么try子句余下的部分将被忽略。如果异常的类型和 except 之后的名称相符，那么对应的except子句将被执行。最后执行 try 语句之后的代码; 如果一个异常没有与任何的except匹配，那么这个异常将会传递给上层的try中;一个 try 语句可能包含多个except子句，分别来处理不同的特定的异常。最多只有一个分支会被执行; 处理程序将只针对对应的try子句中的异常进行处理，而不是其他的 try 的处理程序中的异常;<br><a id="more"></a><br>一个except子句可以同时处理多个异常，这些异常将被放在一个括号里成为一个元组，例如:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">except (RuntimeError, TypeError, NameError):</span><br><span class="line">    pass</span><br></pre></td></tr></table></figure></p>
<p>最后一个except子句可以忽略异常的名称，它将被当作通配符使用。你可以使用这种方法打印一个错误信息，然后再次把异常抛出。<br>示例：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">import sys</span><br><span class="line"></span><br><span class="line">try:</span><br><span class="line">	f = open(&apos;myfile.txt&apos;)</span><br><span class="line">	s = f.readline()</span><br><span class="line">	i = int(s.strip())</span><br><span class="line">	pass</span><br><span class="line">except OSError as err:</span><br><span class="line">	print(&quot;OS error: &#123;0&#125;&quot;.format(err))</span><br><span class="line">except ValueError:</span><br><span class="line">	print(&quot;Could not convert data to an integer&quot;)</span><br><span class="line">except:</span><br><span class="line">	print(&quot;Unexpected error:&quot;, sys.exc_info()[0])</span><br><span class="line">	pass</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-d10119bc65d6daac.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图1.png"></p>
<p>2). try except 语句还有一个可选的else子句，如果使用这个子句，那么必须放在所有的except子句之后。这个子句将在try子句没有发生任何异常的时候执行。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">for arg in sys.argv[1:]:</span><br><span class="line">    try:</span><br><span class="line">        f = open(arg, &apos;r&apos;)</span><br><span class="line">    except IOError:</span><br><span class="line">        print(&apos;cannot open&apos;, arg)</span><br><span class="line">    else:</span><br><span class="line">        print(arg, &apos;has&apos;, len(f.readlines()), &apos;lines&apos;)</span><br><span class="line">        f.close()</span><br></pre></td></tr></table></figure></p>
<p>3). 抛出异常<br>raise 唯一的一个参数指定了要被抛出的异常。它必须是一个异常的实例或者是异常的类（也就是 Exception 的子类）.如果你只想知道这是否抛出了一个异常，并不想去处理它，那么一个简单的 raise 语句就可以再次把它抛出。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">try:</span><br><span class="line">        raise NameError(&apos;HiThere&apos;)</span><br><span class="line">    except NameError:</span><br><span class="line">        print(&apos;An exception flew by!&apos;)</span><br><span class="line">        raise</span><br></pre></td></tr></table></figure></p>
<p>4). 用户自定义异常<br>通过创建一个新的exception类来拥有自己的异常。异常应该继承自 Exception 类，或者直接继承，或者间接继承<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">class MyError(Exception):</span><br><span class="line">        def __init__(self, value):</span><br><span class="line">            self.value = value</span><br><span class="line">        def __str__(self):</span><br><span class="line">            return repr(self.value)</span><br></pre></td></tr></table></figure></p>
<p>5). 定义清理行为<br>try 语句还有另外一个可选的子句，它定义了无论在任何情况下都会执行的清理行为。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">try:</span><br><span class="line">    raise KeyboardInterrupt</span><br><span class="line">finally:</span><br><span class="line">    print(&apos;Goodbye, world!&apos;)</span><br></pre></td></tr></table></figure></p>
<p>6). 预定义的清理行为<br>一些对象定义了标准的清理行为，无论系统是否成功的使用了它，一旦不需要它了，那么这个标准的清理行为就会执行。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">with open(&quot;myfile.txt&quot;) as f:</span><br><span class="line">    for line in f:</span><br><span class="line">        print(line, end=&quot;&quot;)</span><br></pre></td></tr></table></figure></p>
<p>####2. 面向对象技术简介</p>
<ul>
<li>类(Class): 用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。对象是类的实例。</li>
<li>类变量：类变量在整个实例化的对象中是公用的。类变量定义在类中且在函数体之外。类变量通常不作为实例变量使用。</li>
<li>数据成员：类变量或者实例变量用于处理类及其实例对象的相关的数据。</li>
<li>方法重写：如果从父类继承的方法不能满足子类的需求，可以对其进行改写，这个过程叫方法的覆盖（override），也称为方法的重写。</li>
<li>实例变量：定义在方法中的变量，只作用于当前实例的类。</li>
<li>继承：即一个派生类（derived class）继承基类（base class）的字段和方法。继承也允许把一个派生类的对象作为一个基类对象对待。例如，有这样一个设计：一个Dog类型的对象派生自Animal类，这是模拟”是一个（is-a）”关系（例图，Dog是一个Animal）。</li>
<li>实例化：创建一个类的实例，类的具体对象。</li>
<li>方法：类中定义的函数。</li>
<li>对象：通过类定义的数据结构实例。对象包括两个数据成员（类变量和实例变量）和方法。<br>####3. 类定义<br>语法格式如下：<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">class ClassName:</span><br><span class="line">    &lt;statement-1&gt;</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    &lt;statement-N&gt;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>类实例化后，可以使用其属性，实际上，创建一个类之后，可以通过类名访问其属性。</p>
<p>####4. 类对象<br>类对象支持两种操作：属性引用和实例化。属性引用使用和 Python 中所有的属性引用一样的标准语法：obj.name。类对象创建后，类命名空间中所有的命名都是有效属性名。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"># 定义类</span><br><span class="line">class MyClass(object):</span><br><span class="line">	&quot;&quot;&quot;一个简单的类实例&quot;&quot;&quot;</span><br><span class="line">	i = 123</span><br><span class="line">	def f(self):</span><br><span class="line">		return &quot;Hello World!&quot;</span><br><span class="line">		pass</span><br><span class="line">		</span><br><span class="line"></span><br><span class="line"># 实例化类</span><br><span class="line">x = MyClass()</span><br><span class="line"></span><br><span class="line"># 访问类的属性和方法</span><br><span class="line">print(&quot;MyClass 类的属性 i 为：&quot;, x.i)</span><br><span class="line">print(&quot;MyClass 类的方法 f 输出：&quot;, x.f())</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-2e0769462475f359.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图2.png"></p>
<p>####5. 构造函数__init__()<br>self代表类的实例，而非类，类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称, 按照惯例它的名称是 self。self 代表的是类的实例，代表当前对象的地址，而 self.class 则指向类。self 不是 python 关键字，我们把他换成 runoob 也是可以正常执行的:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"># 定义类</span><br><span class="line">class Complex(object):</span><br><span class="line">	&quot;&quot;&quot;docstring for Comples&quot;&quot;&quot;</span><br><span class="line">	def __init__(self, realpart, imagpart):</span><br><span class="line">		super(Complex, self).__init__()</span><br><span class="line">		self.r = realpart</span><br><span class="line">		self.i = imagpart</span><br><span class="line"></span><br><span class="line"># 创建类</span><br><span class="line">x = Complex(3.0, -2.4)</span><br><span class="line">print(x.r, x.i)</span><br></pre></td></tr></table></figure>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-cc20d842935f85be.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图3.png"></p>
<p>####6. 类的方法<br>在类地内部，使用 def 关键字来定义一个方法，与一般函数定义不同，类方法必须包含参数 self, 且为第一个参数，self 代表的是类的实例。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"># 类定义</span><br><span class="line">class people(object):</span><br><span class="line">	&quot;&quot;&quot;docstring for people&quot;&quot;&quot;</span><br><span class="line">	# 定义基本属性 </span><br><span class="line">	name = &quot;&quot;</span><br><span class="line">	age = 0</span><br><span class="line">	# 定义私有属性， 私有属性在类外部无法直接访问</span><br><span class="line">	__weight = 0</span><br><span class="line">	# 定义构造方法</span><br><span class="line">	def __init__(self, name, age, weight):</span><br><span class="line">		super(people, self).__init__()</span><br><span class="line">		self.name = name</span><br><span class="line">		self.age = age</span><br><span class="line">		self.__weight = weight</span><br><span class="line">	def speak(self):</span><br><span class="line">		print(&quot;%s 说：我 %d 岁。&quot; %(self.name, self.age))</span><br><span class="line">		pass</span><br><span class="line"></span><br><span class="line"># 实例化类</span><br><span class="line">p = people(&quot;mazaiting&quot;, 24, 60)</span><br><span class="line">p.speak()</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-8163c57f4fa5533f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图4.png"></p>
<p>####7. 继承<br>Python 同样支持类的继承，如果一种语言不支持继承，类就没有什么意义。派生类的定义如下所示:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">class DerivedClassName(BaseClassName1):</span><br><span class="line">    &lt;statement-1&gt;</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    &lt;statement-N&gt;</span><br></pre></td></tr></table></figure></p>
<p>需要注意圆括号中基类的顺序，若是基类中有相同的方法名，而在子类使用时未指定，python从左至右搜索 即方法在子类中未找到时，从左到右查找基类中是否包含方法。<br>BaseClassName（示例中的基类名）必须与派生类定义在一个作用域内。除了类，还可以用表达式，基类定义在另一个模块中时这一点非常有用:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">class DerivedClassName(modname.BaseClassName):</span><br></pre></td></tr></table></figure></p>
<p>示例：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"># 类定义</span><br><span class="line">class people(object):</span><br><span class="line">	&quot;&quot;&quot;docstring for people&quot;&quot;&quot;</span><br><span class="line">	# 定义基本属性 </span><br><span class="line">	name = &quot;&quot;</span><br><span class="line">	age = 0</span><br><span class="line">	# 定义私有属性， 私有属性在类外部无法直接访问</span><br><span class="line">	__weight = 0</span><br><span class="line">	# 定义构造方法</span><br><span class="line">	def __init__(self, name, age, weight):</span><br><span class="line">		super(people, self).__init__()</span><br><span class="line">		self.name = name</span><br><span class="line">		self.age = age</span><br><span class="line">		self.__weight = weight</span><br><span class="line">	def speak(self):</span><br><span class="line">		print(&quot;%s 说：我 %d 岁。&quot; %(self.name, self.age))</span><br><span class="line">		pass</span><br><span class="line"></span><br><span class="line"># 单继承</span><br><span class="line">class student(people):</span><br><span class="line">	&quot;&quot;&quot;docstring for student&quot;&quot;&quot;</span><br><span class="line">	grade = &quot;&quot;</span><br><span class="line">	def __init__(self, name, age, weight, grade):</span><br><span class="line">		super(student, self).__init__(name, age, weight)</span><br><span class="line">		self.grade = grade</span><br><span class="line">	# 复写父类方法</span><br><span class="line">	def speak(self):</span><br><span class="line">		print(&quot;%s 说：我 %d 岁了，我在读 %d年级&quot; %(self.name, self.age, self.grade))</span><br><span class="line">		pass</span><br><span class="line"></span><br><span class="line">s = student(&quot;John&quot;, 12, 40, 6)</span><br><span class="line">s.speak()</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-f418655bab3398c6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图5.png"></p>
<p>####8. 多继承<br>Python同样有限的支持多继承形式。多继承的类定义形如下例:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">class DerivedClassName(Base1, Base2, Base3):</span><br><span class="line">    &lt;statement-1&gt;</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    &lt;statement-N&gt;</span><br></pre></td></tr></table></figure></p>
<p>需要注意圆括号中父类的顺序，若是父类中有相同的方法名，而在子类使用时未指定，python从左至右搜索 即方法在子类中未找到时，从左到右查找父类中是否包含方法。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"># 类定义</span><br><span class="line">class people(object):</span><br><span class="line">	&quot;&quot;&quot;docstring for people&quot;&quot;&quot;</span><br><span class="line">	# 定义基本属性 </span><br><span class="line">	name = &quot;&quot;</span><br><span class="line">	age = 0</span><br><span class="line">	# 定义私有属性， 私有属性在类外部无法直接访问</span><br><span class="line">	__weight = 0</span><br><span class="line">	# 定义构造方法</span><br><span class="line">	def __init__(self, name, age, weight):</span><br><span class="line">		super(people, self).__init__()</span><br><span class="line">		self.name = name</span><br><span class="line">		self.age = age</span><br><span class="line">		self.__weight = weight</span><br><span class="line">	def speak(self):</span><br><span class="line">		print(&quot;%s 说：我 %d 岁。&quot; %(self.name, self.age))</span><br><span class="line">		pass</span><br><span class="line"></span><br><span class="line"># 单继承</span><br><span class="line">class student(people):</span><br><span class="line">	&quot;&quot;&quot;docstring for student&quot;&quot;&quot;</span><br><span class="line">	grade = &quot;&quot;</span><br><span class="line">	def __init__(self, name, age, weight, grade):</span><br><span class="line">		super(student, self).__init__(name, age, weight)</span><br><span class="line">		self.grade = grade</span><br><span class="line">	# 复写父类方法</span><br><span class="line">	def speak(self):</span><br><span class="line">		print(&quot;%s 说：我 %d 岁了，我在读 %d年级&quot; %(self.name, self.age, self.grade))</span><br><span class="line">		pass</span><br><span class="line"></span><br><span class="line"># 演讲者类</span><br><span class="line">class speaker(object):</span><br><span class="line">	&quot;&quot;&quot;docstring for speaker&quot;&quot;&quot;</span><br><span class="line">	topic = &quot;&quot;</span><br><span class="line">	name = &quot;&quot;</span><br><span class="line">	def __init__(self, name, topic):</span><br><span class="line">		# super(speaker, self).__init__()</span><br><span class="line">		self.name = name</span><br><span class="line">		self.topic = topic</span><br><span class="line">	def speak(self):</span><br><span class="line">		print(&quot;我叫%s, 我是一个演说家，我演讲的主题是%s&quot;%(self.name, self.topic))</span><br><span class="line">		pass</span><br><span class="line"></span><br><span class="line"># 多重继承</span><br><span class="line">class sample(speaker, student):</span><br><span class="line">	&quot;&quot;&quot;docstring for sample&quot;&quot;&quot;</span><br><span class="line">	def __init__(self, name, age, weight, grade, topic):</span><br><span class="line">		student.__init__(self, name, age, weight, grade)</span><br><span class="line">		speaker.__init__(self, name, topic)</span><br><span class="line"></span><br><span class="line">test = sample(&quot;mazaiting&quot;, 24, 60, 6, &quot;Python&quot;)</span><br><span class="line"># 方法名同， 调用的是在括号中排前的父类的方法</span><br><span class="line">test.speak()</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-807821048049a408.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图6.png"></p>
<p>####9. 方法重写<br>如果你的父类方法的功能不能满足你的需求，你可以在子类重写你父类的方法<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"># 方法重写</span><br><span class="line"># 定义父类</span><br><span class="line">class Parent(object):</span><br><span class="line">	&quot;&quot;&quot;docstring for Parent&quot;&quot;&quot;</span><br><span class="line">	def myMethod(self):</span><br><span class="line">		print(&quot;调用父类方法&quot;)</span><br><span class="line">		pass</span><br><span class="line"></span><br><span class="line"># 定义子类</span><br><span class="line">class Child(object):</span><br><span class="line">	&quot;&quot;&quot;docstring for Child&quot;&quot;&quot;</span><br><span class="line">	def myMethod(self):</span><br><span class="line">		print(&quot;调用子类方法&quot;)</span><br><span class="line">		pass</span><br><span class="line"></span><br><span class="line"># 子类实例</span><br><span class="line">c = Child()</span><br><span class="line"># 子类调用重写方法</span><br><span class="line">c.myMethod()</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-99933e06548fc5af.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图7.png"></p>
<p>####10. 类属性与方法</p>
<ul>
<li>类的私有属性<br><strong>private_attrs：两个下划线开头，声明该属性为私有，不能在类地外部被使用或直接访问。在类内部的方法中使用时 self.</strong>private_attrs。</li>
<li>类的方法<br>在类地内部，使用 def 关键字来定义一个方法，与一般函数定义不同，类方法必须包含参数 self，且为第一个参数，self 代表的是类的实例。<br>self 的名字并不是规定死的，也可以使用 this，但是最好还是按照约定是用 self。</li>
<li>类的私有方法<br><strong>private_method：两个下划线开头，声明该方法为私有方法，只能在类的内部调用 ，不能在类地外部调用。self.</strong>private_methods。</li>
</ul>
<p><strong>私有属性</strong>示例：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"># 定义类</span><br><span class="line">class JustCounter(object):</span><br><span class="line">	&quot;&quot;&quot;docstring for JustCounter&quot;&quot;&quot;</span><br><span class="line">	# 私有变量</span><br><span class="line">	__secretCount = 0</span><br><span class="line">	# 公开变量</span><br><span class="line">	publicCount = 0</span><br><span class="line">	def count(self):</span><br><span class="line">		self.__secretCount += 1</span><br><span class="line">		self.publicCount += 1</span><br><span class="line">		print(self.__secretCount)</span><br><span class="line">		pass</span><br><span class="line"></span><br><span class="line">counter = JustCounter()</span><br><span class="line">counter.count()</span><br><span class="line">counter.count()</span><br><span class="line">print(counter.publicCount)</span><br><span class="line"># 报错，实例不能访问私有变量</span><br><span class="line">print(counter.__secretCount)</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-2ce8dc17fb620231.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图8.png"></p>
<p><strong>私有方法</strong>示例：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">class Site(object):</span><br><span class="line">	&quot;&quot;&quot;docstring for Site&quot;&quot;&quot;</span><br><span class="line">	def __init__(self, name, url):</span><br><span class="line">		super(Site, self).__init__()</span><br><span class="line">		# public </span><br><span class="line">		self.name = name</span><br><span class="line">		# private</span><br><span class="line">		self.__url = url</span><br><span class="line"></span><br><span class="line">	def who(self):</span><br><span class="line">		print(&quot;name: &quot;, self.name)</span><br><span class="line">		print(&quot;url: &quot;, self.__url)</span><br><span class="line">		pass</span><br><span class="line"></span><br><span class="line">	# 私有方法</span><br><span class="line">	def __foo():</span><br><span class="line">		print(&quot;这是私有方法&quot;)</span><br><span class="line">		pass</span><br><span class="line"></span><br><span class="line">	# 公共方法</span><br><span class="line">	def foo(self):</span><br><span class="line">		print(&quot;这是公共方法&quot;)</span><br><span class="line">		self.__foo()</span><br><span class="line">		pass</span><br><span class="line">		</span><br><span class="line">x = Site(&quot;百度&quot;, &quot;www.baidu.com&quot;)</span><br><span class="line">x.who()</span><br><span class="line">x.foo()</span><br><span class="line"># 报错</span><br><span class="line">x.__foo()</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-b47c866903de51bd.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图9.png"></p>
<p>####11. 类的专有方法：</p>
<ul>
<li><strong>init</strong> : 构造函数，在生成对象时调用</li>
<li><strong>del</strong> : 析构函数，释放对象时使用</li>
<li><strong>repr</strong> : 打印，转换</li>
<li><strong>setitem</strong> : 按照索引赋值</li>
<li><strong>getitem</strong>: 按照索引获取值</li>
<li><strong>len</strong>: 获得长度</li>
<li><strong>cmp</strong>: 比较运算</li>
<li><strong>call</strong>: 函数调用</li>
<li><strong>add</strong>: 加运算</li>
<li><strong>sub</strong>: 减运算</li>
<li><strong>mul</strong>: 乘运算</li>
<li><strong>div</strong>: 除运算</li>
<li><strong>mod</strong>: 求余运算</li>
<li><strong>pow</strong>: 乘方</li>
</ul>
<p>####12. 运算符重载<br>Python同样支持运算符重载，我们可以对类的专有方法进行重载<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"># 运算符重载</span><br><span class="line">class Vector(object):</span><br><span class="line">	&quot;&quot;&quot;docstring for Vector&quot;&quot;&quot;</span><br><span class="line">	def __init__(self, a, b):</span><br><span class="line">		super(Vector, self).__init__()</span><br><span class="line">		self.a = a</span><br><span class="line">		self.b = b</span><br><span class="line"></span><br><span class="line">	def __str__(self):</span><br><span class="line">		return &quot;Vector (%d, %d)&quot; % (self.a, self.b)</span><br><span class="line">		pass</span><br><span class="line">		</span><br><span class="line">	def __add__(self, other):</span><br><span class="line">		return Vector(self.a + other.a, self.b + other.b)</span><br><span class="line">		pass</span><br><span class="line"></span><br><span class="line">v1 = Vector(2, 10)</span><br><span class="line">v2 = Vector(5, -2)</span><br><span class="line">print(v1 + v2)</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-5e07170991cf225a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图10.png"></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/08/06/Python/Python-学习(二)/" rel="next" title="Python-学习(二)">
                <i class="fa fa-chevron-left"></i> Python-学习(二)
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/08/06/Python/Python-学习(八)--网络操作/" rel="prev" title="Python-学习(八)--网络操作">
                Python-学习(八)--网络操作 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpeg"
                alt="凌浩雨" />
            
              <p class="site-author-name" itemprop="name">凌浩雨</p>
              <p class="site-description motion-element" itemprop="description">专业从事于移动端开发，Android与iOS均有涉及，主做Android开发与React Native开发</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">393</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">凌浩雨</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
